package shiyl.use.springboot.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import shiyl.use.springboot.config.CustomerDefinition;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static java.lang.String.format;

/**
 * 自定义参数管理Controller
 * @author shiyl
 */

@RestController
public class ConfigController {


    @Autowired
    CustomerDefinition customerDefinition ;

    @Autowired
    Environment environment ;

    /**
     * 从Spring的Environment对象中找配置
     * @param keyFullName 配置全路径名称
     * @return
     */
    @GetMapping("/spring/{keyFullName}")
    public String getPropertiesFromEnvironment(@PathVariable  String keyFullName){

        String value = environment.getProperty(keyFullName);
        if( null == value || value.equals("") ){
            return "未找到 key="+keyFullName+"的值" ;
        }
        return format("%s=%s",keyFullName,value ) ;
    }


    /**
     * 获取指定key的自定义参数信息
     * keyName与待获取参数同名
     * 参数项命名规则遵守小驼峰(首字母小写，以大小字母分割单词)
     * 所有参数值均转为String形式
     * @return
     */
    @GetMapping("/customer/{keyName}")
    public String getCustomerProperties(@PathVariable String keyName){

        String getKeyMethodName = "get" + StringUtils.capitalize(keyName);
        try {
            Method getKeyMethod = customerDefinition.getClass().getMethod(getKeyMethodName);
            if( null == getKeyMethod.invoke(customerDefinition) ){
                throw new RuntimeException(format("参数 %s 不存在值!",keyName)) ;
            }
            String value = getKeyMethod.invoke(customerDefinition).toString() ;

            return format("找到自定义参数： %s = %s ",keyName, value) ;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            throw new RuntimeException(format("找不到获取参数项[%s]的方法[%s]",keyName,getKeyMethodName)) ;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException(format("不让访问方法%s",getKeyMethodName) );
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            throw new RuntimeException(format("执行获取参数方法 %s 失败 " ,getKeyMethodName) );
        }
    }

    /**
     * 把Environment注入到CustomerDefinition中，
     * 然后借CustomerDefinition对象获取Spring中的配置
     * @return
     */
    @GetMapping("/customer/active")
    public String getProfilesActive(){
        return customerDefinition.getProfileActive() ;
    }

}
